<template>
  <div>
    <el-dialog
      :visible.sync="isVisible"
      title="角色分配"
      center
      width="634px"
      :close-on-press-escape="false"
      :close-on-click-modal="false"
    >
      <!--穿梭框-->
      <el-transfer
        v-model="authIds"
        :titles="['未授权用户', '已授权用户']"
        filterable
        filter-placeholder="请输入账号"
        :data="users"
      />
      <!--Footer-->
      <div slot="footer" class="dialog-footer">
        <el-button size="mini" @click="isVisible = false">
          取 消
        </el-button>
        <el-button
          type="primary"
          size="mini"
          :loading="loading"
          @click="assignHandle()"
        >
          确 定
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'RoleAssign',
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    roleId: {
      type: [String, Number],
      default: 0
    }
  },
  data() {
    return {
      users: [],
      authIds: [],
      loading: false
    }
  },
  computed: {
    isVisible: {
      get() {
        return this.visible
      },
      set(val) {
        this.$emit('update:visible', val)
      }
    }
  },
  watch: {
    isVisible(val) {
      if (val) {
        this.listAssign()
      }
    }
  },
  methods: {
    listAssign() {
      this.users = []
      this.authIds = []
      this.AjaxUtils.get('/role/listAssign', { roleId: this.roleId }).then(response => {
        // 所有用户
        const users = response.data.users
        users.forEach(item => {
          this.users.push({ key: item.id, label: item.username, disabled: item === 'admin' })
        })
        // 已授权用户
        const authIds = response.data.authIds
        authIds.forEach(item => {
          this.authIds.push(item)
        })
      }).catch()
    },
    assignHandle() {
      // authIds
      let userIds = ''
      this.authIds.forEach(item => {
        userIds = userIds + item + ','
      })
      // params
      const params = new URLSearchParams()
      params.append('roleId', this.roleId)
      params.append('userIds', userIds)
      // ajax
      this.loading = true
      this.AjaxUtils.post('/role/assign', params, true).then(response => {
        this.loading = false
        if (response.code === 0) {
          this.isVisible = false
          this.$emit('reloadTable')
        }
      }).catch(() => {
        this.loading = false
      })
    }
  }
}
</script>

<style lang="scss" scoped>
</style>
